package org.kenewstar.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.kenewstar.common.constant.CommonConstant;
import org.kenewstar.common.utils.CommonResult;
import org.kenewstar.common.utils.UrlResourceRelease;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xinke.huang@hand-china.com
 * @version 1.0
 * @date 2021/3/2
 */
@Component
public class LoginFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取RequestContext对象
        RequestContext context = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = context.getRequest();
        // 获取session
        HttpSession session = request.getSession();
        Object user = session.getAttribute(CommonConstant.SESSION_USER);
        // 获取请求路径
        String url = request.getRequestURI();
        boolean release = UrlResourceRelease.isContainUrl(url);
        // 包含,放行资源
        if (release) { return false; }
        return Objects.isNull(user);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        try {
            context.setResponseBody(toJson(CommonResult.failed("会话已失效，请重新登录")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 响应json格式字符串
     * @param obj 响应对象
     * @throws IOException 异常类型
     */
    private static void responseBody(Object obj) throws IOException {
        // 获取requestContext
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.setSendZuulResponse(false);
        // 获取response
        HttpServletResponse response = requestContext.getResponse();
        response.setStatus(200);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(toJson(obj));

    }
    /**
     * 将对象转换为json格式字符串
     * @param obj 转换对象
     * @return jsonString
     * @throws JsonProcessingException 异常类型
     */
    private static String toJson(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }
}
